﻿using KPIS.GERP.ESS.APP.App_UI.Commons;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.DAL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace KPIS.GERP.ESS.APP.App_UI.Forms
{
    public partial class ESS_ProjectOperationEdit : System.Web.UI.Page
    {
        Main main = new Main();
        D_BgmProjectOperationEdit edit = new D_BgmProjectOperationEdit();

        BGM_MAS_Source.BGM_MAS_Source source = new BGM_MAS_Source.BGM_MAS_Source();
        BGM_Project.BGM_Project pj = new BGM_Project.BGM_Project();
        BGM_ProjectExpense.BGM_ProjectExpense pjexp = new BGM_ProjectExpense.BGM_ProjectExpense();
        BGM_ProjectReport.BGM_ProjectReport pjrpt = new BGM_ProjectReport.BGM_ProjectReport();
        BGM_ProjectOperation.BGM_ProjectOperation op = new BGM_ProjectOperation.BGM_ProjectOperation();
        BGM_ProjectOperationExpense.BGM_ProjectOperationExpense opexp = new BGM_ProjectOperationExpense.BGM_ProjectOperationExpense();
        BGM_ProjectOperationPerson.BGM_ProjectOperationPerson opper = new BGM_ProjectOperationPerson.BGM_ProjectOperationPerson();
        D_BgmProjectOperation opDal = new D_BgmProjectOperation();
        BGM_MAS_Option.BGM_MAS_Option option = new BGM_MAS_Option.BGM_MAS_Option();
        B_HrmEmployees emp = new B_HrmEmployees();
        FIM_Employees.FIM_Employees emp2 = new FIM_Employees.FIM_Employees();

        ESS.BLL.B_MessageSend send = new ESS.BLL.B_MessageSend();
        ESS.BLL.B_MessageReply reply = new ESS.BLL.B_MessageReply();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetDefault();
                cmdArival_Click(null, null);
            }
        }

        protected void SetUI(Mode mode, string RecordStatus)
        {
            switch (mode)
            {
                case Mode.AddNew:
                    PanelViewAll.Visible = false;
                    PanelEdit.Visible = true;

                    cmdCancel.Visible = true;
                    cmdEdit1.Visible = false;
                    cmdReport.Visible = false;
                    cmdSendMessage1.Visible = false;
                    cmdUpdate1.Visible = false;
                    cmdAddNew1.Visible = false;
                    cmdInsert1.Visible = true;
                    cmdCancelMessage.Visible = false;
                    break;
                case Mode.Edit:
                    PanelViewAll.Visible = false;
                    PanelEdit.Visible = true;

                    cmdCancel.Visible = true;
                    cmdEdit1.Visible = false;
                    cmdReport.Visible = true;
                    cmdSendMessage1.Visible = RecordStatus == "W" || RecordStatus == "R";
                    cmdUpdate1.Visible = RecordStatus == "W" || RecordStatus == "R";
                    cmdAddNew1.Visible = false;
                    cmdInsert1.Visible = false;
                    cmdCancelMessage.Visible = false;
                    break;
                case Mode.Arival:
                    PanelViewAll.Visible = true;
                    PanelEdit.Visible = false;

                    cmdCancel.Visible = false;
                    cmdEdit1.Visible = false;
                    cmdReport.Visible = false;
                    cmdSendMessage1.Visible = false;
                    cmdUpdate1.Visible = false;
                    cmdAddNew1.Visible = true;
                    cmdInsert1.Visible = false;
                    cmdCancelMessage.Visible = false;

                    cmdArival.CssClass = "LinkButtonBigBorder";
                    cmdHistory.CssClass = "LinkButtonBigNoBorder";

                    LoadGrdViewAll();

                    GrdViewAll.Visible = true;
                    GrdViewAll2.Visible = false;
                    break;
                case Mode.History:
                    PanelViewAll.Visible = true;
                    PanelEdit.Visible = false;

                    cmdCancel.Visible = false;
                    cmdEdit1.Visible = true;
                    cmdReport.Visible = false;
                    cmdSendMessage1.Visible = false;
                    cmdUpdate1.Visible = false;
                    cmdAddNew1.Visible = false;
                    cmdInsert1.Visible = false;
                    cmdCancelMessage.Visible = false;

                    cmdArival.CssClass = "LinkButtonBigNoBorder";
                    cmdHistory.CssClass = "LinkButtonBigBorder";

                    LoadGrdViewAll2();

                    GrdViewAll.Visible = false;
                    GrdViewAll2.Visible = true;
                    break;
            }
        }

        protected void SetDefault()
        {
            int year = main.GetSystemControls().default_bgm_year.Value;
            txtBgmYear.Text = year.ToString();
            txtBgmYear.MinValue = year;
            txtBgmYear.MaxValue = year + 1;

            txtBgmProjOperEditDate.SetValue(DateTime.Today);
            txtRemarks.Text = "";
        }

        protected void LoadGrdViewAll()
        {
            string strBgmYear = txtBgmYear.Text;

            GrdViewAll.DataSource = op.GetFull(null, strBgmYear, SsMng.WorkingJobSiteSeq
                , null, null, false, true);
            GrdViewAll.DataBind();
        }

        protected void LoadGrdViewAll2()
        {
            int? nBgmYear = main.ConvertNullInt(txtBgmYear.Text);

            GrdViewAll2.DataSource = edit.GetFull(nBgmYear, SsMng.WorkingJobSiteSeqI);
            GrdViewAll2.DataBind();
        }

        protected void LoadRepeater4(BGM_ProjectOperation.M_BGM_ProjectOperation model)
        {
            double dSumRemainAmount = 0;
            double dSumProjAmount = 0;
            string strBgmProjSeq = model.bgm_proj_seq.ToString();
            string strBgmProjOperSeq = model.bgm_proj_oper_seq.ToString();

            IList<BGM_Project.M_BGM_Project> infoList = pj.GetBudget(strBgmProjSeq, null, null);
            Repeater4.DataSource = infoList;
            Repeater4.DataBind();

            for (int i = 0; i < infoList.Count; i++)
            {
                dSumRemainAmount = dSumRemainAmount + infoList[i].remain_amount.Value;
                dSumProjAmount = dSumProjAmount + infoList[i].project_amount.Value;
            }

            lblSumRemainAmount.Text = dSumRemainAmount.ToString("#,###.00");
            lblSumProjectAmount.Text = dSumProjAmount.ToString("#,###.00");
        }

        protected void LoadGrdBgmProjectOperationExpense(BGM_ProjectOperation.M_BGM_ProjectOperation model)
        {
            grdBgmProjectOperationExpense.DataSource = opexp.GetProjectExpense(model.bgm_proj_oper_seq.ToString(), model.bgm_proj_seq.ToString());

            GridGroupByExpression group1 = new GridGroupByExpression(grdBgmProjectOperationExpense.Columns.FindByUniqueName("m_bgm_projectexpense.m_bgm_mas_source.bgm_source_name"));
            GridGroupByExpression group2 = new GridGroupByExpression(grdBgmProjectOperationExpense.Columns.FindByUniqueName("m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_name"));

            grdBgmProjectOperationExpense.MasterTableView.GroupByExpressions.Add(group1);
            grdBgmProjectOperationExpense.MasterTableView.GroupByExpressions.Add(group2);
            grdBgmProjectOperationExpense.DataBind();

            double dTotalAmount = 0;
            foreach (GridDataItem item in grdBgmProjectOperationExpense.Items)
            {
                RadNumericTextBox txtAmount1 = (RadNumericTextBox)item.FindControl("txtAmount");
                dTotalAmount += txtAmount1.Value ?? 0;
            }

            lblFinSumAmount.Text = dTotalAmount.ToString("#,##0.00");
        }

        protected void LoadGrdBgmProjectOperationExpense2(M_BGM_ProjectOperationEdit editModel, BGM_ProjectOperation.M_BGM_ProjectOperation opModel)
        {
            grdBgmProjectOperationExpense.DataSource = opexp.GetProjectExpense2(editModel.bgm_proj_oper_seq.Value, opModel.bgm_proj_seq.Value, editModel.bgm_proj_oper_edit_seq);

            GridGroupByExpression group1 = new GridGroupByExpression(grdBgmProjectOperationExpense.Columns.FindByUniqueName("m_bgm_projectexpense.m_bgm_mas_source.bgm_source_name"));
            GridGroupByExpression group2 = new GridGroupByExpression(grdBgmProjectOperationExpense.Columns.FindByUniqueName("m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_name"));

            grdBgmProjectOperationExpense.MasterTableView.GroupByExpressions.Add(group1);
            grdBgmProjectOperationExpense.MasterTableView.GroupByExpressions.Add(group2);
            grdBgmProjectOperationExpense.DataBind();

            double dTotalAmount = 0;
            foreach (GridDataItem item in grdBgmProjectOperationExpense.Items)
            {
                RadNumericTextBox txtAmount1 = (RadNumericTextBox)item.FindControl("txtAmount");
                dTotalAmount += txtAmount1.Value ?? 0;
            }

            lblFinSumAmount.Text = dTotalAmount.ToString("#,##0.00");
        }

        protected void SetEmpInfo(string strEmpSeq)
        {
            if (strEmpSeq.Length > 0)
            {
                DataTable dtb = emp.GetInfo(Convert.ToInt32(strEmpSeq));

                lblApproveEmpSeq.Text = dtb.Rows[0]["sequence"].ToString();
                lblApprovePosSeq.Text = dtb.Rows[0]["t_pos_seq"].ToString();
                //lblApproverName.Text = dtb.Rows[0]["full_name"].ToString();
                lblPosName.Text = dtb.Rows[0]["pos_name"].ToString();
                lblClassName.Text = dtb.Rows[0]["class_name"].ToString();
                lblExecPosName.Text = dtb.Rows[0]["exec_pos_name"].ToString();
                lblJobsiteName.Text = dtb.Rows[0]["job_site_name"].ToString();
                ddlApprover.Text = dtb.Rows[0]["full_name"].ToString();
            }
        }

        protected void LoadApprover()
        {
            // Edit by Aek 2014-07-29
            // Calculate base on to_emp_seq field in table message_send, not login session 
            DataTable dtb = send.GetCurrentApprover(SsMng.EmpSeq, null, "BGM_PROJECT_OPERATION", 1);
            

            if (dtb != null)
            {
                if (dtb.Rows.Count > 0)
                {
                    lblApprovePathSeq.Text = dtb.Rows[0]["approve_path_seq"].ToString();
                    SetEmpInfo(dtb.Rows[0]["emp_seq"].ToString());
                }
            }
        }

        protected void ddlApprover_DataBound(object sender, EventArgs e)
        {
            //set the initial footer label
            ((Literal)ddlApprover.Footer.FindControl("RadComboItemsCount")).Text = Convert.ToString(ddlApprover.Items.Count);
        }

        protected void ddlApprover_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            ddlApprover.DataSource = emp.ListEmployeeByType("('1', '2', '3')", "");
            ddlApprover.DataBind();
        }

        protected void ddlApprover_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            SetEmpInfo(ddlApprover.SelectedValue);
        }

        protected void ddlApprover_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((DataRowView)e.Item.DataItem)["full_name"].ToString();
            e.Item.Value = ((DataRowView)e.Item.DataItem)["sequence"].ToString();
        }

        protected void cmdSendMessage1_Click(object sender, EventArgs e)
        {
            PanelMessageSend.Visible = true;
            ddlApprover.SelectedIndex = -1;
            lblClassName.Text = "";
            lblExecPosName.Text = "";
            lblJobsiteName.Text = "";
            lblPosName.Text = "";
            lblApproveEmpSeq.Text = "";
            lblApprovePosSeq.Text = "";

            LoadApprover();
        }

        protected void cmdAddNew1_Click(object sender, EventArgs e)
        {
            if (GrdViewAll.SelectedItems.Count > 0)
            {
                string strBgmProjOperSeq = main.WebString(((GridDataItem)GrdViewAll.SelectedItems[0])["bgm_proj_oper_seq"].Text);
                BGM_ProjectOperation.M_BGM_ProjectOperation model = op.GetInfo(strBgmProjOperSeq);

                if (model.m_bgm_project != null)
                {
                    lblFinBgmProjName.Text = model.m_bgm_project.bgm_proj_name;
                    lblFinBgmActName.Text = model.m_bgm_project.m_bgm_activity != null ? model.m_bgm_project.m_bgm_activity.bgm_strat_list_name : "-";
                    lblFinBgmSubActName.Text = model.m_bgm_project.m_bgm_subactivity != null ? model.m_bgm_project.m_bgm_subactivity.bgm_strat_list_name : "-";
                    lblFinBgmOutputName.Text = model.m_bgm_project.m_bgm_output != null ? model.m_bgm_project.m_bgm_output.bgm_strat_list_name : "-";
                }

                lblFinBgmProjOperEditSeq.Text = "";
                lblFinBgmProjSeq.Text = model.bgm_proj_seq.ToString();
                lblFinBgmProjOperSeq.Text = model.bgm_proj_oper_seq.ToString();
                lblFinBgmProjOperCode.Text = model.bgm_proj_oper_code;
                lblFinBgmProjOperDate.Text = model.bgm_proj_oper_date.HasValue ? model.bgm_proj_oper_date.Value.ToLongDateString() : "-";
                lblFinBgmProjOperName.Text = model.bgm_proj_oper_name;
                lblFinBgmYear.Text = model.bgm_year.ToString();
                lblFinStartDate.Text = model.start_date.HasValue ? model.start_date.Value.ToLongDateString() : "-";
                lblFinEndDate.Text = model.end_date.HasValue ? model.end_date.Value.ToLongDateString() : "-";
                lblFinRecordStatus.Text = model.record_status;
                lblFinAttendCount.Text = model.attend_count.HasValue ? model.attend_count.Value.ToString("#,##0") : "-";

                lblSendBackRemark.Text = "";
                tableSendBackRemark.Visible = false;

                switch (model.record_status)
                {
                    case "W":
                        lblFinRecordStatusName.Text = "ดำเนินการอยู่";
                        lblFinRecordStatusName.ForeColor = System.Drawing.Color.Red;
                        cmdSendMessage1.Visible = true;
                        break;
                    case "P":
                        lblFinRecordStatusName.Text = "รอการอนุมัติโดย " + send.GetLatestMessageStatus(strBgmProjOperSeq, "bgm_project_operation").to_user_name;
                        lblFinRecordStatusName.ForeColor = System.Drawing.Color.Blue;
                        cmdSendMessage1.Visible = false;
                        break;
                    case "A":
                        lblFinRecordStatusName.Text = "อนุมัติโดย " + send.GetLatestMessageStatus(strBgmProjOperSeq, "bgm_project_operation").to_user_name;
                        lblFinRecordStatusName.ForeColor = System.Drawing.Color.Green;
                        cmdSendMessage1.Visible = false;
                        break;
                    case "R":
                        lblFinRecordStatusName.Text = "ตีกลับ " + send.GetLatestMessageStatus(strBgmProjOperSeq, "bgm_project_operation").to_user_name;
                        lblFinRecordStatusName.ForeColor = System.Drawing.Color.Red;
                        cmdSendMessage1.Visible = true;
                        tableSendBackRemark.Visible = true;

                        var replys = reply.GetInfoFromRefSeq(strBgmProjOperSeq, "bgm_project_operation");

                        if (replys.Count > 0)
                        {
                            lblSendBackRemark.Text = replys[0].remarks;
                        }

                        //lblSendBackRemark.Text = reply.GetInfoFromRefSeq(strBgmProjOperSeq, "bgm_project_operation")[0].remarks;
                        //lblSendBackRemark.Text = reply.GetInfoFromRefSeq(strBgmProjOperSeq, "bgm_project_operation")[0].remarks;
                        break;
                    default:
                        lblFinRecordStatusName.Text = "รอการยืนยัน " + send.GetLatestMessageStatus(strBgmProjOperSeq, "bgm_project_operation").to_user_name;
                        lblFinRecordStatusName.ForeColor = System.Drawing.Color.Red;
                        cmdSendMessage1.Visible = true;
                        break;
                }

                IList<BGM_MAS_Option.M_BGM_MAS_Option> optionInfoList = option.GetListFromBgmProjSeq("3", model.bgm_proj_seq.ToString());// HardCode
                Repeater2.DataSource = optionInfoList;
                Repeater2.DataBind();

                IList<BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson> personInfoList = opper.GetFull(strBgmProjOperSeq);
                Repeater3.DataSource = personInfoList;
                Repeater3.DataBind();

                txtBgmProjOperEditDate.SetValue(DateTime.Today);
                txtRemarks.Text = "";

                LoadRepeater4(model);
                LoadGrdBgmProjectOperationExpense(model);
                SetUI(Mode.AddNew, null);
            }
            else
            {
                main.MessageAlert(Page, "กรุณาเลือกรายการอนุมัติดำเนินงานที่ต้องการแก้ไข");
            }
        }

        protected void cmdInsert1_Click(object sender, EventArgs e)
        {
            try
            {
                string strBgmProjOperSeq = lblFinBgmProjOperSeq.Text;
                string strBgmProjSeq = lblFinBgmProjSeq.Text;

                if (txtBgmProjOperEditDate.GetDateValue() == null)
                {
                    main.MessageAlert(Page, "กรุณากรอกข้อมูลวันที่");
                    return;
                }

                Dictionary<int, double> dicRemainAmount = new Dictionary<int, double>();
                Dictionary<int, double> dicAddAmount = new Dictionary<int, double>();
                var sourceModels = source.GetList();
                foreach (var sourceModel in sourceModels)
                {
                    dicAddAmount.Add(sourceModel.bgm_source_seq, 0);
                    dicRemainAmount.Add(sourceModel.bgm_source_seq, opDal.GetProjectRemainAmount(main.ConvertNullInt(strBgmProjSeq), sourceModel.bgm_source_seq));
                }

                foreach (GridDataItem item in grdBgmProjectOperationExpense.Items)
                {
                    int nBgmSourceSeq = main.ConvertNullInt(item["m_bgm_projectexpense.bgm_source_seq"].Text) ?? 0;
                    double dAddAmount = ((RadNumericTextBox)item.FindControl("txtAmount")).Value ?? 0;

                    dicAddAmount[nBgmSourceSeq] += dAddAmount;
                }

                foreach (var subDicAddAmount in dicAddAmount)
                {
                    if (subDicAddAmount.Value > dicRemainAmount[subDicAddAmount.Key])
                    {
                        main.MessageAlert(Page, "จำนวนเงินที่ขออนุมัติเพิ่มมากกว่าจำนวนเงินคงเหลือของโครงการ");
                        return;
                    }
                }

                M_BGM_ProjectOperationEdit model = new M_BGM_ProjectOperationEdit
                {
                    bgm_proj_oper_edit_date = txtBgmProjOperEditDate.GetDateValue(),
                    bgm_proj_oper_seq = main.ConvertNullInt(strBgmProjOperSeq),
                    emp_seq = SsMng.EmpSeqI,
                    remarks = txtRemarks.Text,
                    record_status = "W",
                    created_by = SsMng.EmpSeqI,
                };

                int bgm_proj_oper_edit_seq = edit.Insert(model);

                foreach (GridDataItem item in grdBgmProjectOperationExpense.Items)
                {
                    RadNumericTextBox txtAddAmount = (RadNumericTextBox)item.FindControl("txtAmount");
                    double? dAddAmount = txtAddAmount.Value;

                    if (dAddAmount.HasValue && dAddAmount.Value >= 0)
                    {
                        M_BGM_ProjectOperationEditExpense expenseModel = new M_BGM_ProjectOperationEditExpense
                        {
                            bgm_proj_oper_edit_seq = bgm_proj_oper_edit_seq,
                            bgm_proj_exp_seq = main.ConvertNullInt(main.WebString(item["bgm_proj_exp_seq"].Text)),
                            bgm_proj_oper_exp_seq = main.ConvertNullInt(main.WebString(item["bgm_proj_oper_exp_seq"].Text)),
                            old_amount = main.ConvertNullDouble(((Label)item["amount"].FindControl("lblOldAmount")).Text) ?? 0,
                            add_amount = dAddAmount ?? 0,
                            created_by = SsMng.EmpSeqI,
                        };

                        edit.InsertExpense(expenseModel);
                    }
                }

                main.MessageAlert(Page, "รหัสรายการคือ [" + edit.GetInfo(bgm_proj_oper_edit_seq).bgm_proj_oper_edit_code + "]");
                SetUI(Mode.History, null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void cmdUpdate1_Click(object sender, EventArgs e)
        {
            try
            {
                string strBgmProjOperEditSeq = lblFinBgmProjOperEditSeq.Text;
                string strBgmProjOperSeq = lblFinBgmProjOperSeq.Text;
                string strBgmProjSeq = lblFinBgmProjSeq.Text;

                if (txtBgmProjOperEditDate.GetDateValue() == null)
                {
                    main.MessageAlert(Page, "กรุณากรอกข้อมูลวันที่");
                    return;
                }

                Dictionary<int, double> dicRemainAmount = new Dictionary<int, double>();
                Dictionary<int, double> dicAddAmount = new Dictionary<int, double>();
                var sourceModels = source.GetList();
                foreach (var sourceModel in sourceModels)
                {
                    dicAddAmount.Add(sourceModel.bgm_source_seq, 0);
                    dicRemainAmount.Add(sourceModel.bgm_source_seq, opDal.GetProjectRemainAmount(main.ConvertNullInt(strBgmProjSeq), sourceModel.bgm_source_seq));
                }

                foreach (GridDataItem item in grdBgmProjectOperationExpense.Items)
                {
                    int nBgmSourceSeq = main.ConvertNullInt(item["m_bgm_projectexpense.bgm_source_seq"].Text) ?? 0;
                    double dAddAmount = ((RadNumericTextBox)item.FindControl("txtAmount")).Value ?? 0;

                    dicAddAmount[nBgmSourceSeq] += dAddAmount;
                }

                foreach (var subDicAddAmount in dicAddAmount)
                {
                    if (subDicAddAmount.Value > dicRemainAmount[subDicAddAmount.Key])
                    {
                        main.MessageAlert(Page, "จำนวนเงินที่ขออนุมัติเพิ่มมากกว่าจำนวนเงินคงเหลือของโครงการ");
                        return;
                    }
                }

                M_BGM_ProjectOperationEdit model = new M_BGM_ProjectOperationEdit
                {
                    bgm_proj_oper_edit_seq = main.ConvertNullInt(strBgmProjOperEditSeq) ?? 0,
                    bgm_proj_oper_edit_date = txtBgmProjOperEditDate.GetDateValue(),
                    bgm_proj_oper_seq = main.ConvertNullInt(strBgmProjOperSeq),
                    emp_seq = SsMng.EmpSeqI,
                    remarks = txtRemarks.Text,
                    updated_by = SsMng.EmpSeqI,
                };

                edit.Update(model);

                foreach (GridDataItem item in grdBgmProjectOperationExpense.Items)
                {
                    int? bgm_proj_oper_edit_exp_seq = main.ConvertNullInt(main.WebString(item["bgm_proj_oper_edit_exp_seq"].Text));
                    RadNumericTextBox txtAddAmount = (RadNumericTextBox)item.FindControl("txtAmount");
                    double? dAddAmount = txtAddAmount.Value;

                    if (dAddAmount.HasValue && dAddAmount.Value >= 0)
                    {
                        M_BGM_ProjectOperationEditExpense expenseModel = new M_BGM_ProjectOperationEditExpense
                        {
                            bgm_proj_oper_edit_seq = main.ConvertNullInt(strBgmProjOperEditSeq) ?? 0,
                            bgm_proj_exp_seq = main.ConvertNullInt(main.WebString(item["bgm_proj_exp_seq"].Text)),
                            bgm_proj_oper_exp_seq = main.ConvertNullInt(main.WebString(item["bgm_proj_oper_exp_seq"].Text)),
                            old_amount = main.ConvertNullDouble(((Label)item["amount"].FindControl("lblOldAmount")).Text) ?? 0,
                            add_amount = dAddAmount ?? 0,
                            created_by = SsMng.EmpSeqI,
                            updated_by = SsMng.EmpSeqI,
                        };

                        if (!bgm_proj_oper_edit_exp_seq.HasValue)
                        {
                            edit.InsertExpense(expenseModel);
                        }
                        else
                        {
                            expenseModel.bgm_proj_oper_edit_exp_seq = bgm_proj_oper_edit_exp_seq ?? 0;

                            edit.UpdateExpense(expenseModel);
                        }
                    }
                    else if (bgm_proj_oper_edit_exp_seq.HasValue)
                    {
                        edit.DeleteExpense(bgm_proj_oper_edit_exp_seq ?? 0);
                    }
                }

                main.MessageAlert(Page, "บันทึกรายการเรียบร้อย");
                SetUI(Mode.History, null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void cmdEdit1_Click(object sender, EventArgs e)
        {
            if (GrdViewAll2.SelectedItems.Count > 0)
            {
                int nBgmProjOperEditSeq = main.ConvertNullInt(main.WebString(((GridDataItem)GrdViewAll2.SelectedItems[0])["bgm_proj_oper_edit_seq"].Text)) ?? 0;
                Session["ReportSeq"] = nBgmProjOperEditSeq;
                M_BGM_ProjectOperationEdit editModel = edit.GetInfo(nBgmProjOperEditSeq);
                BGM_ProjectOperation.M_BGM_ProjectOperation opModel = op.GetInfo(editModel.bgm_proj_oper_seq.HasValue ? editModel.bgm_proj_oper_seq.ToString() : "0");

                if (opModel.m_bgm_project != null)
                {
                    lblFinBgmProjName.Text = opModel.m_bgm_project.bgm_proj_name;
                    lblFinBgmActName.Text = opModel.m_bgm_project.m_bgm_activity != null ? opModel.m_bgm_project.m_bgm_activity.bgm_strat_list_name : "-";
                    lblFinBgmSubActName.Text = opModel.m_bgm_project.m_bgm_subactivity != null ? opModel.m_bgm_project.m_bgm_subactivity.bgm_strat_list_name : "-";
                    lblFinBgmOutputName.Text = opModel.m_bgm_project.m_bgm_output != null ? opModel.m_bgm_project.m_bgm_output.bgm_strat_list_name : "-";
                }
                
                lblFinBgmProjSeq.Text = opModel.bgm_proj_seq.ToString();
                lblFinBgmProjOperSeq.Text = opModel.bgm_proj_oper_seq.ToString();
                lblFinBgmProjOperCode.Text = opModel.bgm_proj_oper_code;
                lblFinBgmProjOperDate.Text = opModel.bgm_proj_oper_date.HasValue ? opModel.bgm_proj_oper_date.Value.ToLongDateString() : "-";
                lblFinBgmProjOperName.Text = opModel.bgm_proj_oper_name;
                lblFinBgmYear.Text = opModel.bgm_year.ToString();
                lblFinStartDate.Text = opModel.start_date.HasValue ? opModel.start_date.Value.ToLongDateString() : "-";
                lblFinEndDate.Text = opModel.end_date.HasValue ? opModel.end_date.Value.ToLongDateString() : "-";
                lblFinRecordStatus.Text = opModel.record_status;
                lblFinAttendCount.Text = opModel.attend_count.HasValue ? opModel.attend_count.Value.ToString("#,##0") : "-";

                lblSendBackRemark.Text = "";
                tableSendBackRemark.Visible = false;

                lblBgmProjOperEditCode.Text = editModel.bgm_proj_oper_edit_code;
                lblFinBgmProjOperEditSeq.Text = editModel.bgm_proj_oper_edit_seq.ToString();
                txtRemarks.Text = editModel.remarks;
                txtBgmProjOperEditDate.SetValue(editModel.bgm_proj_oper_edit_date);

                switch (editModel.record_status)
                {
                    case "W":
                        lblFinRecordStatusName.Text = "ดำเนินการอยู่";
                        lblFinRecordStatusName.ForeColor = System.Drawing.Color.Red;
                        cmdSendMessage1.Visible = true;
                        break;
                    case "P":
                        lblFinRecordStatusName.Text = "รอการอนุมัติโดย " + send.GetLatestMessageStatus(nBgmProjOperEditSeq.ToString(), "bgm_project_operation_edit").to_user_name;
                        lblFinRecordStatusName.ForeColor = System.Drawing.Color.Blue;
                        cmdSendMessage1.Visible = false;
                        break;
                    case "A":
                        lblFinRecordStatusName.Text = "อนุมัติโดย " + send.GetLatestMessageStatus(nBgmProjOperEditSeq.ToString(), "bgm_project_operation_edit").to_user_name;
                        lblFinRecordStatusName.ForeColor = System.Drawing.Color.Green;
                        cmdSendMessage1.Visible = false;
                        break;
                    case "R":
                        lblFinRecordStatusName.Text = "ตีกลับ " + send.GetLatestMessageStatus(nBgmProjOperEditSeq.ToString(), "bgm_project_operation_edit").to_user_name;
                        lblFinRecordStatusName.ForeColor = System.Drawing.Color.Red;
                        cmdSendMessage1.Visible = true;
                        tableSendBackRemark.Visible = true;

                        var replys = reply.GetInfoFromRefSeq(nBgmProjOperEditSeq.ToString(), "bgm_project_operation_edit");

                        if (replys.Count > 0)
                        {
                            lblSendBackRemark.Text = replys[0].remarks;
                        }

                        //lblSendBackRemark.Text = reply.GetInfoFromRefSeq(strBgmProjOperSeq, "bgm_project_operation")[0].remarks;
                        //lblSendBackRemark.Text = reply.GetInfoFromRefSeq(nBgmProjOperEditSeq.ToString(), "bgm_project_operation_edit")[0].remarks;
                        break;
                    default:
                        lblFinRecordStatusName.Text = "รอการยืนยัน " + send.GetLatestMessageStatus(nBgmProjOperEditSeq.ToString(), "bgm_project_operation_edit").to_user_name;
                        lblFinRecordStatusName.ForeColor = System.Drawing.Color.Red;
                        cmdSendMessage1.Visible = true;
                        break;
                }

                IList<BGM_MAS_Option.M_BGM_MAS_Option> optionInfoList = option.GetListFromBgmProjSeq("3", opModel.bgm_proj_seq.ToString());// HardCode
                Repeater2.DataSource = optionInfoList;
                Repeater2.DataBind();

                IList<BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson> personInfoList = opper.GetFull(opModel.bgm_proj_oper_seq.ToString());
                Repeater3.DataSource = personInfoList;
                Repeater3.DataBind();

                LoadRepeater4(opModel);
                LoadGrdBgmProjectOperationExpense2(editModel, opModel);
                SetUI(Mode.Edit, editModel.record_status);
                string strMessageStatus = send.GetInfoFromRefSeq(nBgmProjOperEditSeq.ToString(), "bgm_project_operation_edit").message_status;
                cmdCancelMessage.Visible = strMessageStatus == "0";
            }
            else
            {
                main.MessageAlert(Page, "กรุณาเลือกรายการขออนุมัติดำเนินงานเพิ่มที่ต้องการแก้ไข");
            }
        }

        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            cmdHistory_Click(null, null);
        }

        protected void GrdViewAll_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                string strRecordStatus = ((GridDataItem)e.Item)["record_status"].Text;
                TableCell cell = ((GridDataItem)e.Item)["record_status_name"];

                switch (strRecordStatus)
                {
                    case "W":
                    default:
                        cell.ForeColor = System.Drawing.Color.Red;
                        break;
                    case "P":
                        cell.ForeColor = System.Drawing.Color.Blue;
                        break;
                    case "A":
                        cell.ForeColor = System.Drawing.Color.Green;
                        break;
                }
            }
        }

        protected void GrdViewAll_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "Filter" || e.CommandName == "Sort" || e.CommandName == "Page")
            {
                LoadGrdViewAll();
            }
        }

        protected void GrdViewAll2_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                string strRecordStatus = ((GridDataItem)e.Item)["record_status"].Text;
                TableCell cell = ((GridDataItem)e.Item)["record_status_name"];

                switch (strRecordStatus)
                {
                    case "W":
                    default:
                        cell.ForeColor = System.Drawing.Color.Red;
                        break;
                    case "P":
                        cell.ForeColor = System.Drawing.Color.Blue;
                        break;
                    case "A":
                        cell.ForeColor = System.Drawing.Color.Green;
                        break;
                }
            }
        }

        protected void GrdViewAll2_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "Filter" || e.CommandName == "Sort" || e.CommandName == "Page")
            {
                LoadGrdViewAll2();
            }
        }

        protected void txtAmount_TextChanged(object sender, EventArgs e)
        {
            double dTotalAmount = 0;
            RadNumericTextBox txtAmount = (RadNumericTextBox)sender;
            Label lblNewAmount = (Label)txtAmount.Parent.FindControl("lblNewAmount");
            Label lblOldAmount = (Label)txtAmount.Parent.FindControl("lblOldAmount");

            double dAmount = txtAmount.Value ?? 0;
            double dOldAmount = main.ConvertNullDouble(lblOldAmount.Text) ?? 0;
            lblNewAmount.Text = (dAmount + dOldAmount).ToString("#,##0.00");

            foreach (GridDataItem item in grdBgmProjectOperationExpense.Items)
            {
                RadNumericTextBox txtAmount1 = (RadNumericTextBox)item.FindControl("txtAmount");
                dTotalAmount += txtAmount1.Value ?? 0;
            }

            lblFinSumAmount.Text = dTotalAmount.ToString("#,##0.00");
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            if (lblApproveEmpSeq.Text.Length == 0)
            {
                ((RadAjaxManager)Master.FindControl("RadAjaxManager1")).Alert("คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง");
                return;
            }

            try
            {
                string strBgmProjOperEditSeq = lblFinBgmProjOperEditSeq.Text;
                ESS.MODEL.M_MessageSend info = new ESS.MODEL.M_MessageSend();
                info.send_date = DateTime.Today;
                info.ref_seq = main.ConvertNullInt(strBgmProjOperEditSeq);
                info.ref_type = "bgm_project_operation_edit";
                info.ref_no = lblBgmProjOperEditCode.Text;
                info.send_text = "ส่งคำขอแก้ไขอนุมัติดำเนินงาน : " + lblFinBgmProjOperCode.Text + " : " + lblFinBgmProjOperName.Text;
                info.from_emp_seq = main.ConvertNullInt(Session["EmpSeq"]);
                info.to_emp_seq = main.ConvertNullInt(lblApproveEmpSeq.Text);

                info.from_pos_seq = emp2.GetInfo(Session["EmpSeq"].ToString()).pos_seq;
                info.to_pos_seq = main.ConvertNullInt(lblApprovePosSeq.Text);
                info.wod_emp_seq = null;

                info.from_send_seq = null;
                info.remarks = null;
                info.message_status = "0";
                info.approve_path_seq = main.ConvertNullInt(lblApprovePathSeq.Text);
                info.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                info.created_when = DateTime.Now;
                send.Insert(info);

                edit.ChangeStatus(Convert.ToInt32(strBgmProjOperEditSeq), "P", main.ConvertNullInt(Session["EmpSeq"]) ?? 0);
                ((RadAjaxManager)Master.FindControl("RadAjaxManager1")).Alert("บันทึกเรียบร้อยแล้ว");

                PanelMessageSend.Visible = false;
                SetUI(Mode.History, null);
            }
            catch
            {
                ((RadAjaxManager)Master.FindControl("RadAjaxManager1")).Alert("เกิดข้อผิดพลาดในการบันทึกข้อมูล");
            }
        }

        protected void cmdCloseExpenseSummary_Click(object sender, ImageClickEventArgs e)
        {
            PanelExpenseSummary.Visible = false;
        }

        protected void cmdOpenExpenseSummary_Click(object sender, EventArgs e)
        {
            PanelExpenseSummary.Visible = true;
        }

        protected void cmdArival_Click(object sender, EventArgs e)
        {
            SetUI(Mode.Arival, null);
        }

        protected void cmdHistory_Click(object sender, EventArgs e)
        {
            SetUI(Mode.History, null);
        }

        protected void cmdCancelMessage_Click(object sender, EventArgs e)
        {
            var message = send.GetInfoFromRefSeq(lblFinBgmProjOperEditSeq.Text, "bgm_project_operation_edit");
            message.updated_by = SsMng.EmpSeqI;
            message.updated_when = DateTime.Now;
            send.Delete(message);

            edit.ChangeStatus(main.ConvertNullInt(lblFinBgmProjOperEditSeq.Text) ?? 0, "W", SsMng.EmpSeqI);
            SetUI(Mode.History, null);
        }
    }

    public enum Mode
    {
        AddNew,
        Edit,
        Arival,
        History
    }
}